package sddz.foodmanage.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.bigkoo.pickerview.TimePickerView;
import com.google.gson.Gson;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.header.progresslayout.ProgressLayout;
import com.zhy.autolayout.AutoLinearLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.Request;
import sddz.foodmanage.R;
import sddz.foodmanage.activity.LoginActivity;
import sddz.foodmanage.activity.OrderDetailActivity;
import sddz.foodmanage.adapter.UniversalAdapter;
import sddz.foodmanage.adapter.UniversalViewHolder;
import sddz.foodmanage.base.BasePageFragment;
import sddz.foodmanage.dialog.PingjiWindow;
import sddz.foodmanage.dialog.ZhongduiWindow;
import sddz.foodmanage.model.DoneListBean;
import sddz.foodmanage.model.PingjiBean;
import sddz.foodmanage.model.ZhongduiListBean;
import sddz.foodmanage.utils.API;
import sddz.foodmanage.utils.HttpUtils;
import sddz.foodmanage.utils.SpfUtils;
import sddz.foodmanage.view.MyListView;
import sddz.foodmanage.activity.AddSelfBuyActivity;

/**
 * /**
 *
 * @Date:2019/7/9
 * @Author:lbb 管理员的订单页面
 * 中队的其他页面
 * 供应商的已完成页面
 * 中队的已完成页面（没有中队的选择）
 */
public class DoneOrderFragment extends BasePageFragment {


    @BindView(R.id.tv_pingji)
    TextView tvPingji;
    @BindView(R.id.tv_zhongdui)
    TextView tvZhongdui;
    @BindView(R.id.tv_starttime)
    TextView tvStarttime;
    @BindView(R.id.tv_endtime)
    TextView tvEndtime;
    @BindView(R.id.tv_totalmoney)
    TextView tvTotalmoney;
    @BindView(R.id.tv_query)
    TextView tvQuery;

    @BindView(R.id.gather_trl)
    TwinklingRefreshLayout gatherTrl;
    Unbinder unbinder;
    @BindView(R.id.tv_zanwu)
    TextView tvZanwu;
    @BindView(R.id.all_zdcheck)
    AutoLinearLayout allZdcheck;
    @BindView(R.id.tv_addselfbuy)
    TextView tvAddSelfBuy;

    @BindView(R.id.gather_listView)
    MyListView gatherListView;
    private TimePickerView pvTime;
    private boolean isChooseBirth = true;//开始时间，false 结束时间
    private String starttime;//开始时间
    private String endtime;//结束时间
    private PingjiWindow pjwindow;//评级弹窗
    private ZhongduiWindow zdwindow;//中队弹窗
    List<PingjiBean> pjlist;
    private String pingjiid;//评级id
    private String zhongduiid = "0";//中队id
    static int stype;
    private List<ZhongduiListBean.DataBean> zdlist = new ArrayList<>();
    private List<DoneListBean.DataBeanX.PaginatorBean.DataBean> datalist = new ArrayList<>();//查询到的数据集合
    private DoneListBean doneListBean;//查询到的数据集合
    private String key;
    private String other;
    private UniversalAdapter<DoneListBean.DataBeanX.PaginatorBean.DataBean> adapter;
    int pages = 1;

    public DoneOrderFragment() {
        // Required empty public constructor
    }

    public static DoneOrderFragment newInstance(String stype) {

        Bundle args = new Bundle();
        args.putString("types", stype);
        DoneOrderFragment fragment = new DoneOrderFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_done_order, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        initData();
        initListener();
        view.setClickable(true);
        return view;
    }

    @Override
    public void fetchData() {
        getZhongdui();
        queryddata(pages);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            initView();
        }
    }

    private void initListener() {
        gatherTrl.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                pages = 1;
                queryddata(pages);
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);
                pages++;
                queryddata(pages);
            }
        });

        pjwindow.setOnNationItemListener(new PingjiWindow.OnpjItemListener() {
            @Override
            public void nation(String nation, String code) {
                pingjiid = code;
                tvPingji.setText(nation);
                pages = 1;
            }
        });
        zdwindow.setOnzdItemListener(new ZhongduiWindow.OnzdItemListener() {
            @Override
            public void nation(String nation, String nationCode) {
                zhongduiid = nationCode;
                tvZhongdui.setText(nation);
                pages = 1;
            }
        });
        adapter = new UniversalAdapter<DoneListBean.DataBeanX.PaginatorBean.DataBean>(mActivity, datalist, R.layout.item_wait) {
            @Override
            public void convert(UniversalViewHolder holder, int position, DoneListBean.DataBeanX.PaginatorBean.DataBean dataBean) {
                if (!TextUtils.isEmpty(key) && key.equals("已完成")) {//中队
                    holder.setText(R.id.tv_wait_orderid, dataBean.getNumber());
                } else if (!TextUtils.isEmpty(key) && key.equals("其他")) {//中队
                    holder.setText(R.id.tv_wait_orderid, dataBean.getDetachment().getName() +
                            "(" + dataBean.getSupplier().getName() + ")");
                } else if (!TextUtils.isEmpty(key) && key.equals("订单")) {//管理员;
                    holder.setText(R.id.tv_wait_orderid, dataBean.getDetachment().getName() +
                            "(" + dataBean.getSupplier().getName() + ")");
                } else if (!TextUtils.isEmpty(key) && key.equals("供应商完成")) {//供应商完成
                    holder.setText(R.id.tv_wait_orderid, dataBean.getDetachment().getName());

                }
//                holder.setText(R.id.tv_wait_orderid,dataBean.getNumber());
                holder.setText(R.id.tv_wait_time, dataBean.getChecked_time());
                holder.setText(R.id.tv_money, dataBean.getTotal_price() + "元");
                TextView tvpj = holder.getView(R.id.tv_pj);
                tvpj.setVisibility(View.VISIBLE);
                String s_pj = dataBean.getComment().getGrade_desc() + "";
                if(s_pj.equals("null")){
                    holder.setText(R.id.tv_pj, "自");
                }else {
                    holder.setText(R.id.tv_pj, dataBean.getComment().getGrade_desc() + "");
                }
                holder.setText(R.id.tv_delivery_time, dataBean.getDelivery_time());
            }
        };
        gatherListView.setAdapter(adapter);
        gatherListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//                if(key.equals("已完成")||key.equals("其他")){
                Intent intent = new Intent(mActivity, OrderDetailActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("data", datalist.get(i));
                bundle.putInt("position", i);
                bundle.putString("status", "已完成");
                intent.putExtras(bundle);
                startActivity(intent);
//                }

            }
        });
    }

    private void initData() {
        key = (String) getArguments().get("types");
        Log.e("types", key);
        if (key.equals("已完成")) {//中队
            other = 5 + "";
            allZdcheck.setVisibility(View.GONE);
            tvAddSelfBuy.setVisibility(View.VISIBLE);
        } else if (key.equals("其他")) {//中队
            other = "other";
            allZdcheck.setVisibility(View.VISIBLE);
            tvAddSelfBuy.setVisibility(View.GONE);
        } else if (key.equals("订单")) {//管理员;
            other = 5 + "";
            allZdcheck.setVisibility(View.VISIBLE);
            tvAddSelfBuy.setVisibility(View.GONE);
        } else if (key.equals("供应商完成")) {//供应商完成
            other = 5 + "";
            allZdcheck.setVisibility(View.VISIBLE);
            tvAddSelfBuy.setVisibility(View.GONE);

        }

        PingjiBean pjbean0 = new PingjiBean();
        pjbean0.setPjid("");
        pjbean0.setPjname("请选择");
        PingjiBean pjbean1 = new PingjiBean();
        pjbean1.setPjid("1");
        pjbean1.setPjname("优");
        PingjiBean pjbean2 = new PingjiBean();
        pjbean2.setPjid("2");
        pjbean2.setPjname("良");
        PingjiBean pjbean3 = new PingjiBean();
        pjbean3.setPjid("3");
        pjbean3.setPjname("中");
        PingjiBean pjbean4 = new PingjiBean();
        pjbean4.setPjid("4");
        pjbean4.setPjname("差");
        pjlist = new ArrayList<>();
        pjlist.add(pjbean0);
        pjlist.add(pjbean1);
        pjlist.add(pjbean2);
        pjlist.add(pjbean3);
        pjlist.add(pjbean4);
        pjwindow.setData(pjlist);
//        fetchData();

    }

    private void initView() {

        Date date = new Date();

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

        String sim = dateFormat.format(date);
        starttime = sim;
        tvStarttime.setText(sim);
        endtime = sim;
        tvEndtime.setText(sim);
        //时间选择器
        pvTime = new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                String date1 = new SimpleDateFormat("yyyy-MM-dd").format(date);
                String date2 = new SimpleDateFormat("yyyy-MM-dd").format(date);
                pages = 1;
                if (isChooseBirth) {
                    starttime = date1;
                    tvStarttime.setText(date2);
                } else {
                    endtime = date1;
                    tvEndtime.setText(date2);
                }
            }
        }).setType(new boolean[]{true, true, true, false, false, false}).setCancelColor(getResources().getColor(R.color.gray_text))
                .setSubmitColor(getResources().getColor(R.color.title_color)).build();

        pvTime.setDate(Calendar.getInstance());
        pjwindow = new PingjiWindow((AppCompatActivity) getActivity());
        zdwindow = new ZhongduiWindow((AppCompatActivity) getActivity());
        ProgressLayout progressLayout = new ProgressLayout(mActivity);
        progressLayout.setColorSchemeResources(R.color.colorPrimary);
        gatherTrl.setHeaderView(progressLayout);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.tv_pingji, R.id.tv_zhongdui, R.id.tv_starttime, R.id.tv_endtime, R.id.tv_query, R.id.tv_addselfbuy})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_pingji://评级
                pjwindow.showWindow(view);
                break;
            case R.id.tv_zhongdui://中队
                zdwindow.showWindow(view);
                break;
            case R.id.tv_starttime:
                isChooseBirth = true;
                pvTime.show();
                break;
            case R.id.tv_endtime:
                isChooseBirth = false;
                pvTime.show();
                break;
            case R.id.tv_query://查询
                queryddata(pages);
                break;
            case R.id.tv_addselfbuy://添加自采订单

                startActivityForResult(new Intent(mActivity, AddSelfBuyActivity.class), 1);
                break;
        }
    }

    /**
     * 获取中队列表数据
     */
    private void getZhongdui() {
        baseDialog.show();

        HttpUtils.getInstance().GET(mActivity, API.getzdlist, SpfUtils.gettoken(mActivity), new HttpUtils.OnOkHttpCallback() {
            @Override
            public void onSuccess(String body) {
                baseDialog.dismiss();
                Log.e("获取中队列表0", body);
                if (!TextUtils.isEmpty(body)) {
                    try {
                        JSONObject jsonObject = new JSONObject(body);
                        int code = jsonObject.optInt("status_code");
//                        if (!jsonObject.optString("message").equals("")) {
//                            show(jsonObject.optString("message"));
//                        }
                        if (code == 200) {
                            ZhongduiListBean zhongduiListBean = new Gson().fromJson(body, ZhongduiListBean.class);
                            ZhongduiListBean.DataBean zhongdui = new ZhongduiListBean.DataBean();
                            if (zdlist != null) {
                                zdlist.clear();
                            }
                            zhongdui.setName("请选择");
                            zhongdui.setUser_id(0);
                            zdlist.add(zhongdui);
                            zdlist.addAll(zhongduiListBean.getData());
                            zdwindow.setData(zdlist);
                        } else if (code == 210) {
                            String token = jsonObject.optJSONObject("data").optString("token");
                            SpfUtils.savetoken(mActivity, token);
                            getZhongdui();
                        } else if (code == 401) {
                            SpfUtils.setLogin(mActivity, false);
                            startActivity(new Intent(mActivity, LoginActivity.class));
                            mActivity.finish();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

            }

            @Override
            public void onError(Request error, Exception e) {
                baseDialog.dismiss();
                show("访问数据失败，请稍后重试");
            }
        });

    }

    /**
     * 查询数据
     */
    private void queryddata(final int pages) {
//        if(tvPingji.getText().equals("请选择")){
//            show("请选择评级");
//            return;
//        }
//        if(tvStarttime.getText().equals("请选择")){
//            show("请选择开始时间");
//            return;
//        }
//        if (key.equals("订单")||key.equals("供应商已完成")) {//中队
//            if(tvZhongdui.getText().equals("请选择")){
//                show("请选择中队");
//                return;
//            }
//        }
//        if(tvEndtime.getText().equals("请选择")){
//            show("请选择结束时间");
//            return;
//        }
//        if(!MyUtils.isDateOneBigger(starttime,endtime)){
//            show("开始时间不能大于结束时间");
//            return;
//        }

        Map<String, String> map = new HashMap<>();
        map.put("grade", pingjiid);
        map.put("detachment_id", zhongduiid);//中队登录这个不用传
        map.put("start", starttime);
        map.put("end", endtime);
        map.put("type", other);//其他的传other ,已完成  5
        map.put("current_page", pages + "");//
        Log.e("查询传的数据", JSON.toJSONString(map));
        baseDialog.show();

        HttpUtils.getInstance().POST(mActivity, API.getdoneorderlist, JSON.toJSONString(map), SpfUtils.gettoken(mActivity), new HttpUtils.OnOkHttpCallback() {
            @Override
            public void onSuccess(String body) {
                baseDialog.dismiss();
                Log.e("获取查询列表111", body);
                if (pages == 1) {
                    datalist.clear();
                    gatherTrl.finishRefreshing();
                    adapter.notifyDataSetChanged();

                } else {
                    gatherTrl.finishLoadmore();
                }
                if (!TextUtils.isEmpty(body)) {
                    try {
                        JSONObject jsonObject = new JSONObject(body);
                        int code = jsonObject.optInt("status_code");
//                        if (!jsonObject.optString("message").equals("")) {
//                            show(jsonObject.optString("message"));
//                        }
                        if (code == 200) {
                            doneListBean = new Gson().fromJson(body, DoneListBean.class);
                            if (doneListBean.getData().getPaginator().getData() != null && doneListBean.getData().getPaginator().getTotal() > 0) {
                                if (doneListBean.getData().getPaginator().getData().size() > 0) {
                                    datalist.addAll(doneListBean.getData().getPaginator().getData());
                                    tvTotalmoney.setText(doneListBean.getData().getTotal_price() + "元");
                                    tvZanwu.setVisibility(View.GONE);
                                    gatherListView.setVisibility(View.VISIBLE);
                                    adapter.notifyDataSetChanged();

                                } else {
                                    tvZanwu.setVisibility(View.VISIBLE);
                                    gatherListView.setVisibility(View.GONE);
                                    tvTotalmoney.setText("0" + "元");
                                }
                            } else {
                                if (pages == 1) {
                                    tvZanwu.setVisibility(View.VISIBLE);
                                    gatherListView.setVisibility(View.GONE);
                                    tvTotalmoney.setText("0" + "元");
                                }
//
                                show("没有更多数据了");
                            }

                        } else if (code == 210) {
                            String token = jsonObject.optJSONObject("data").optString("token");
                            SpfUtils.savetoken(mActivity, token);
                            show(jsonObject.optString("message"));
                            getZhongdui();
                        } else if (code == 401) {
                            SpfUtils.setLogin(mActivity, false);
                            show(jsonObject.optString("message"));
                            startActivity(new Intent(mActivity, LoginActivity.class));
                            mActivity.finish();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

            }

            @Override
            public void onError(Request error, Exception e) {
                baseDialog.dismiss();
                show("访问数据失败，请稍后重试");
            }
        });
    }


    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        String result = data.getExtras().getString("result");//得到新Activity 关闭后返回的数据
        if(result.equals("提交成功")){
            queryddata(1);
        }

    }


}
